'use client';

import { useEffect } from 'react';
import { theme } from '../assets/styles/utils';

/**
 * 主题初始化组件
 * 负责在客户端初始化主题系统，避免水合不匹配
 */
export function ThemeInitializer() {
  useEffect(() => {
    // 初始化主题系统
    theme.init();
    
    // 添加键盘用户检测
    let isKeyboardUser = false;
    
    function handleFirstTab(e: KeyboardEvent) {
      if (e.key === 'Tab') {
        document.body.classList.add('keyboard-user');
        isKeyboardUser = true;
        window.removeEventListener('keydown', handleFirstTab);
      }
    }
    
    function handleFirstMouse() {
      if (isKeyboardUser) {
        document.body.classList.remove('keyboard-user');
        isKeyboardUser = false;
      }
      window.removeEventListener('mousedown', handleFirstMouse);
      window.addEventListener('keydown', handleFirstTab);
    }
    
    window.addEventListener('keydown', handleFirstTab);
    window.addEventListener('mousedown', handleFirstMouse);
    
    return () => {
      window.removeEventListener('keydown', handleFirstTab);
      window.removeEventListener('mousedown', handleFirstMouse);
    };
  }, []);

  // 防止水合不匹配的脚本
  useEffect(() => {
    // 确保服务端和客户端渲染一致
    const root = document.documentElement;
    const savedTheme = localStorage.getItem('theme');
    
    if (savedTheme === 'dark') {
      root.classList.add('dark');
    } else if (savedTheme === 'light') {
      root.classList.remove('dark');
    } else {
      // auto 模式
      const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      if (isDark) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
  }, []);

  return null;
} 